8 * Depends on the database object
10 require_once( 'Database.php' );
12 # Valid database indexes
13 # Operation-based indexes
14 define( 'DB_SLAVE', -1 ); # Read from the slave (or only server)
15 define( 'DB_MASTER', -2 ); # Write to master (or only server)
16 define( 'DB_LAST', -3 ); # Whatever database was used last
19 define( 'DB_READ', -1 );
20 define( 'DB_WRITE', -2 );
23 * Database load balancing object
29 /* private */ var $mServers, $mConnections, $mLoads, $mGroupLoads;
30 /* private */ var $mFailFunction, $mErrorConnection;
31 /* private */ var $mForce, $mReadIndex, $mLastIndex;
32 /* private */ var $mWaitForFile, $mWaitForPos, $mWaitTimeout;
33 /* private */ var $mLaggedSlaveMode;
35 function LoadBalancer()
37 $this->mServers
= array();
38 $this->mConnections
= array();
39 $this->mFailFunction
= false;
40 $this->mReadIndex
= -1;
42 $this->mLastIndex
= -1;
43 $this->mErrorConnection
= false;
46 function newFromParams( $servers, $failFunction = false, $waitTimeout = 10 )
48 $lb = new LoadBalancer
;
49 $lb->initialise( $servers, $failFunction, $waitTimeout );
53 function initialise( $servers, $failFunction = false, $waitTimeout = 10 )
55 $this->mServers
= $servers;
56 $this->mFailFunction
= $failFunction;
57 $this->mReadIndex
= -1;
58 $this->mWriteIndex
= -1;
60 $this->mConnections
= array();
61 $this->mLastIndex
= 1;
62 $this->mLoads
= array();
63 $this->mWaitForFile
= false;
64 $this->mWaitForPos
= false;
65 $this->mWaitTimeout
= $waitTimeout;
66 $this->mLaggedSlaveMode
= false;
68 foreach( $servers as $i => $server ) {
69 $this->mLoads
[$i] = $server['load'];
70 if ( isset( $server['groupLoads'] ) ) {
71 foreach ( $server['groupLoads'] as $group => $ratio ) {
72 if ( !isset( $this->mGroupLoads
[$group] ) ) {
73 $this->mGroupLoads
[$group] = array();
75 $this->mGroupLoads
[$group][$i] = $ratio;
82 * Given an array of non-normalised probabilities, this function will select
83 * an element and return the appropriate key
85 function pickRandom( $weights )
87 if ( !is_array( $weights ) ||
count( $weights ) == 0 ) {
92 foreach ( $weights as $w ) {
97 # No loads on any of them
98 # Just pick one at random
99 foreach ( $weights as $i => $w ) {
103 $max = mt_getrandmax();
104 $rand = mt_rand(0, $max) / $max * $sum;
107 foreach ( $weights as $i => $w ) {
109 if ( $sum >= $rand ) {
116 function getRandomNonLagged( $loads ) {
117 # Unset excessively lagged servers
118 $lags = $this->getLagTimes();
119 foreach ( $lags as $i => $lag ) {
120 if ( isset( $this->mServers
[$i]['max lag'] ) && $lag > $this->mServers
[$i]['max lag'] ) {
126 # Find out if all the slaves with non-zero load are lagged
128 foreach ( $loads as $load ) {
132 # No appropriate DB servers except maybe the master and some slaves with zero load
133 # Do NOT use the master
134 # Instead, this function will return false, triggering read-only mode,
135 # and a lagged slave will be used instead.
139 if ( count( $loads ) == 0 ) {
143 #wfDebug( var_export( $loads, true ) );
145 # Return a random representative of the remainder
146 return $this->pickRandom( $loads );
150 * Get the index of the reader connection, which may be a slave
151 * This takes into account load ratios and lag times. It should
152 * always return a consistent index during a given invocation
154 * Side effect: opens connections to databases
156 function getReaderIndex()
158 global $wgMaxLag, $wgReadOnly, $wgDBClusterTimeout;
160 $fname = 'LoadBalancer::getReaderIndex';
161 wfProfileIn( $fname );
164 if ( $this->mForce
>= 0 ) {
167 if ( $this->mReadIndex
>= 0 ) {
168 $i = $this->mReadIndex
;
170 # $loads is $this->mLoads except with elements knocked out if they
172 $loads = $this->mLoads
;
177 $i = $this->pickRandom( $loads );
179 $i = $this->getRandomNonLagged( $loads );
180 if ( $i === false && count( $loads ) != 0 ) {
181 # All slaves lagged. Switch to read-only mode
182 $wgReadOnly = wfMsgNoDB( 'readonly_lag' );
183 $i = $this->pickRandom( $loads );
186 if ( $i !== false ) {
187 wfDebug( "Using reader #$i: {$this->mServers[$i]['host']}...\n" );
188 $this->openConnection( $i );
190 if ( !$this->isOpen( $i ) ) {
191 wfDebug( "Failed\n" );
195 $status = $this->mConnections
[$i]->getStatus();
196 if ( isset( $this->mServers
[$i]['max threads'] ) &&
197 $status['Threads_running'] > $this->mServers
[$i]['max threads'] )
199 # Slave is lagged, wait for a while
200 $sleepTime = 5000 * $status['Threads_connected'];
202 # If we reach the timeout and exit the loop, don't use it
213 $totalElapsed +
= $sleepTime;
214 usleep( $sleepTime );
216 } while ( count( $loads ) && !$done && $totalElapsed / 1e6
< $wgDBClusterTimeout );
218 if ( $i !== false && $this->isOpen( $i ) ) {
219 # Wait for the session master pos for a short time
220 if ( $this->mWaitForFile
) {
221 if ( !$this->doWait( $i ) ) {
222 $this->mServers
[$i]['slave pos'] = $this->mConnections
[$i]->getSlavePos();
225 if ( $i !== false ) {
226 $this->mReadIndex
= $i;
233 wfProfileOut( $fname );
238 * Get a random server to use in a query group
240 function getGroupIndex( $group ) {
241 if ( isset( $this->mGroupLoads
[$group] ) ) {
242 $i = $this->pickRandom( $this->mGroupLoads
[$group] );
246 wfDebug( "Query group $group => $i\n" );
251 * Set the master wait position
252 * If a DB_SLAVE connection has been opened already, waits
253 * Otherwise sets a variable telling it to wait if such a connection is opened
255 function waitFor( $file, $pos ) {
256 $fname = 'LoadBalancer::waitFor';
257 wfProfileIn( $fname );
259 wfDebug( "User master pos: $file $pos\n" );
260 $this->mWaitForFile
= false;
261 $this->mWaitForPos
= false;
263 if ( count( $this->mServers
) > 1 ) {
264 $this->mWaitForFile
= $file;
265 $this->mWaitForPos
= $pos;
266 $i = $this->mReadIndex
;
269 if ( !$this->doWait( $i ) ) {
270 $this->mServers
[$i]['slave pos'] = $this->mConnections
[$i]->getSlavePos();
271 $this->mLaggedSlaveMode
= true;
275 wfProfileOut( $fname );
279 * Wait for a given slave to catch up to the master pos stored in $this
281 function doWait( $index ) {
287 if ( isset( $this->mServers
[$index]['lagged slave'] ) ) {
289 } elseif ( isset( $this->mServers
[$index]['fake slave'] ) ) {
293 $key = 'masterpos:' . $index;
294 $memcPos = $wgMemc->get( $key );
296 list( $file, $pos ) = explode( ' ', $memcPos );
297 # If the saved position is later than the requested position, return now
298 if ( $file == $this->mWaitForFile
&& $this->mWaitForPos
<= $pos ) {
303 if ( !$retVal && $this->isOpen( $index ) ) {
304 $conn =& $this->mConnections
[$index];
305 wfDebug( "Waiting for slave #$index to catch up...\n" );
306 $result = $conn->masterPosWait( $this->mWaitForFile
, $this->mWaitForPos
, $this->mWaitTimeout
);
308 if ( $result == -1 ||
is_null( $result ) ) {
309 # Timed out waiting for slave, use master instead
310 wfDebug( "Timed out waiting for slave #$index pos {$this->mWaitForFile} {$this->mWaitForPos}\n" );
321 * Get a connection by index
323 function &getConnection( $i, $fail = true, $groups = array() )
325 $fname = 'LoadBalancer::getConnection';
326 wfProfileIn( $fname );
330 foreach ( $groups as $group ) {
331 $groupIndex = $this->getGroupIndex( $group );
332 if ( $groupIndex !== false ) {
338 # Operation-based index
339 if ( $i == DB_SLAVE
) {
340 $i = $this->getReaderIndex();
341 } elseif ( $i == DB_MASTER
) {
342 $i = $this->getWriterIndex();
343 } elseif ( $i == DB_LAST
) {
344 # Just use $this->mLastIndex, which should already be set
345 $i = $this->mLastIndex
;
347 # Oh dear, not set, best to use the writer for safety
348 wfDebug( "Warning: DB_LAST used when there was no previous index\n" );
349 $i = $this->getWriterIndex();
352 # Couldn't find a working server in getReaderIndex()?
353 if ( $i === false ) {
354 $this->reportConnectionError( $this->mErrorConnection
);
356 # Now we have an explicit index into the servers array
357 $this->openConnection( $i, $fail );
359 wfProfileOut( $fname );
360 return $this->mConnections
[$i];
364 * Open a connection to the server given by the specified index
365 * Index must be an actual index into the array
369 function openConnection( $i, $fail = false ) {
370 $fname = 'LoadBalancer::openConnection';
371 wfProfileIn( $fname );
374 if ( !$this->isOpen( $i ) ) {
375 $this->mConnections
[$i] = $this->reallyOpenConnection( $this->mServers
[$i] );
378 if ( !$this->isOpen( $i ) ) {
379 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
381 $this->reportConnectionError( $this->mConnections
[$i] );
383 $this->mErrorConnection
= $this->mConnections
[$i];
384 $this->mConnections
[$i] = false;
387 $this->mLastIndex
= $i;
388 wfProfileOut( $fname );
393 * Test if the specified index represents an open connection
396 function isOpen( $index ) {
397 if( !is_integer( $index ) ) {
400 if ( array_key_exists( $index, $this->mConnections
) && is_object( $this->mConnections
[$index] ) &&
401 $this->mConnections
[$index]->isOpen() )
410 * Really opens a connection
413 function reallyOpenConnection( &$server ) {
414 if( !is_array( $server ) ) {
415 wfDebugDieBacktrace( 'You must update your load-balancing configuration. See DefaultSettings.php entry for $wgDBservers.' );
419 # Get class for this database type
420 $class = 'Database' . ucfirst( $type );
421 if ( !class_exists( $class ) ) {
422 require_once( "$class.php" );
426 return new $class( $host, $user, $password, $dbname, 1, $flags );
429 function reportConnectionError( &$conn )
431 $fname = 'LoadBalancer::reportConnectionError';
432 wfProfileIn( $fname );
433 # Prevent infinite recursion
435 static $reporting = false;
438 if ( !is_object( $conn ) ) {
439 $conn = new Database
;
441 if ( $this->mFailFunction
) {
442 $conn->failFunction( $this->mFailFunction
);
444 $conn->failFunction( false );
446 $conn->reportConnectionError();
449 wfProfileOut( $fname );
452 function getWriterIndex()
462 function haveIndex( $i )
464 return array_key_exists( $i, $this->mServers
);
468 * Get the number of defined servers (not the number of open connections)
470 function getServerCount() {
471 return count( $this->mServers
);
475 * Save master pos to the session and to memcached, if the session exists
477 function saveMasterPos() {
478 global $wgSessionStarted;
479 if ( $wgSessionStarted && count( $this->mServers
) > 1 ) {
480 # If this entire request was served from a slave without opening a connection to the
481 # master (however unlikely that may be), then we can fetch the position from the slave.
482 if ( empty( $this->mConnections
[0] ) ) {
483 $conn =& $this->getConnection( DB_SLAVE
);
484 list( $file, $pos ) = $conn->getSlavePos();
485 wfDebug( "Saving master pos fetched from slave: $file $pos\n" );
487 $conn =& $this->getConnection( 0 );
488 list( $file, $pos ) = $conn->getMasterPos();
489 wfDebug( "Saving master pos: $file $pos\n" );
491 if ( $file !== false ) {
492 $_SESSION['master_log_file'] = $file;
493 $_SESSION['master_pos'] = $pos;
499 * Loads the master pos from the session, waits for it if necessary
501 function loadMasterPos() {
502 if ( isset( $_SESSION['master_log_file'] ) && isset( $_SESSION['master_pos'] ) ) {
503 $this->waitFor( $_SESSION['master_log_file'], $_SESSION['master_pos'] );
508 * Close all open connections
510 function closeAll() {
511 foreach( $this->mConnections
as $i => $conn ) {
512 if ( $this->isOpen( $i ) ) {
513 // Need to use this syntax because $conn is a copy not a reference
514 $this->mConnections
[$i]->close();
519 function commitAll() {
520 foreach( $this->mConnections
as $i => $conn ) {
521 if ( $this->isOpen( $i ) ) {
522 // Need to use this syntax because $conn is a copy not a reference
523 $this->mConnections
[$i]->immediateCommit();
528 function waitTimeout( $value = NULL ) {
529 return wfSetVar( $this->mWaitTimeout
, $value );
532 function getLaggedSlaveMode() {
533 return $this->mLaggedSlaveMode
;
538 foreach ( $this->mConnections
as $i => $conn ) {
539 if ( $this->isOpen( $i ) ) {
540 if ( !$this->mConnections
[$i]->ping() ) {
549 * Get the hostname and lag time of the most-lagged slave
550 * This is useful for maintenance scripts that need to throttle their updates
552 function getMaxLag() {
555 foreach ( $this->mServers
as $i => $conn ) {
556 if ( $this->openConnection( $i ) ) {
557 $lag = $this->mConnections
[$i]->getLag();
558 if ( $lag > $maxLag ) {
560 $host = $this->mServers
[$i]['host'];
564 return array( $host, $maxLag );
568 * Get lag time for each DB
569 * Results are cached for a short time in memcached
571 function getLagTimes() {
576 $times = $wgMemc->get( 'lag_times' );
578 # Randomly recache with probability rising over $expiry
579 $elapsed = time() - $times['timestamp'];
580 $chance = max( 0, ( $expiry - $elapsed ) * $requestRate );
581 if ( mt_rand( 0, $chance ) != 0 ) {
582 unset( $times['timestamp'] );
587 # Cache key missing or expired
590 foreach ( $this->mServers
as $i => $conn ) {
591 if ( $this->openConnection( $i ) ) {
592 $times[$i] = $this->mConnections
[$i]->getLag();
596 # Add a timestamp key so we know when it was cached
597 $times['timestamp'] = time();
598 $wgMemc->set( 'lag_times', $times, $expiry );
600 # But don't give the timestamp to the caller
601 unset($times['timestamp']);